{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "76d21526-3476-4cdc-805f-cbf0dba1859a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello world\n"
     ]
    }
   ],
   "source": [
    "print(\"Hello world\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "36ffe6ac-eb50-4ab1-aff5-275f47619362",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello china\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "这是多行注释，用三个单引号\n",
    "这是多行注释，用三个单引号\n",
    "这是多行注释，用三个单引号\n",
    "'''\n",
    "print(\"Hello china\") "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e7ef6c1f-9aea-42bc-8f69-d755b0241f62",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello china\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "这是多行注释，用三个双引号\n",
    "这是多行注释，用三个双引号 \n",
    "这是多行注释，用三个双引号\n",
    "\"\"\"\n",
    "print(\"hello china\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "77ea49b2-695f-431a-b2e8-4c22c0096564",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "print(1 + 1)  # 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f3d634b6-9fc3-4f26-928d-1d0cf03e9b62",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "print(2 - 1)  # 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d936528f-c560-4987-978d-bdd32cfab61a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12\n"
     ]
    }
   ],
   "source": [
    "print(3 * 4)  # 12"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b5eab52d-1fae-4ddf-ab19-f883e73d9cd2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.75\n"
     ]
    }
   ],
   "source": [
    "print(3 / 4)  # 0.75"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "45e007e2-53ef-4ce1-b722-c050d0f58efd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n"
     ]
    }
   ],
   "source": [
    "print(3 // 4)  # 0   整除（地板除）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "4b52b258-f314-4bab-b5c2-eb380bcdaeb3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "print(3 % 4)  # 3   取余"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "70e9dae3-da58-49d6-8d43-84bafa04e2cb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n"
     ]
    }
   ],
   "source": [
    "print(2 ** 3)  # 8   幂"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "47d91f74-f401-4c1f-8473-d1ff9f2c8af5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(2 > 1)  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "bb6876ac-3f02-49c1-9674-7b84279b928c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "print(2 >= 4)  # False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e7eaa02f-e8c6-42fd-97f8-7defdc89ab2a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(1 < 2)  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "90338140-0155-4e20-a591-a2d898b069d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "print(5 <= 2)  # False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "0cf9ee0b-36be-439f-b92b-a82209be9ca9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "print(3 == 4)  # False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "a75c5e26-134e-4820-8dd4-91cc3bc2073b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(3 != 5)  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "08888652-ba79-42ed-a497-9e4a28d16105",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print((3 > 2) and (3 < 5))  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "062c019d-eddc-4184-939f-6d8e7819010c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "print((1 > 3) or (9 < 2))  # False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f685cb1f-7460-4d61-8bef-26a4970376f7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "print(not (2 > 1))  # False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "948e6e12-74ad-42e8-a989-79a35c263cac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b100\n"
     ]
    }
   ],
   "source": [
    "print(bin(4))  # 0b100  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "0640c21f-8cd3-4038-93bf-0c41737809e7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b101\n"
     ]
    }
   ],
   "source": [
    "print(bin(5))  # 0b101"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "4799c888-04db-4fed-98da-81840a04a04d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-0b101 -5\n"
     ]
    }
   ],
   "source": [
    "print(bin(~4), ~4)  # -0b101 -5   按位取反"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "9909b35a-389f-4f30-9dc1-d87bf77756ee",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b100 4\n"
     ]
    }
   ],
   "source": [
    "print(bin(4 & 5), 4 & 5)  # 0b100 4   按位与"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "bde745d3-88ab-4ac6-abe6-a28165c7c01f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b101 5\n"
     ]
    }
   ],
   "source": [
    "print(bin(4 | 5), 4 | 5)  # 0b101 5   按位或"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "26e90703-2591-45b0-84a9-ea2c3a86ba7e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b1 1\n"
     ]
    }
   ],
   "source": [
    "print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1  按位异或"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "575fb091-b0c6-4949-9364-746b8eeb261e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b10000 16\n"
     ]
    }
   ],
   "source": [
    "print(bin(4 << 2), 4 << 2)  # 0b10000 16  左移"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "948ab2d4-a4c8-4851-aa88-1eeb98d8fbe6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b1 1\n"
     ]
    }
   ],
   "source": [
    "print(bin(4 >> 2), 4 >> 2)  # 0b1 1  右移"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "58dbe0cf-411d-43a6-a2ce-920e8f5903b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "#普通写法\n",
    "x, y = 4, 5\n",
    "if x < y:\n",
    "    small = x\n",
    "else:\n",
    "    small = y\n",
    "\n",
    "print(small)  # 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "7b8f7449-1de8-4b7a-9570-fb1578cbfe3e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "#三元运算符\n",
    "x, y = 4, 5\n",
    "small = x if x < y else y\n",
    "print(small)  # 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "a1a582b1-7533-45ab-944c-aaa23826e0a7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A exists\n",
      "h not exists\n"
     ]
    }
   ],
   "source": [
    "# in  and  not in\n",
    "letters = ['A', 'B', 'C']\n",
    "if 'A' in letters:\n",
    "    print('A' + ' exists')\n",
    "if 'h' not in letters:\n",
    "    print('h' + ' not exists')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "5b3d7d71-fa6a-4677-875d-dee9efe3e95a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True True\n",
      "False False\n"
     ]
    }
   ],
   "source": [
    "#比较的两个变量均指向不可变类型。\n",
    "a = \"hello\"\n",
    "b = \"hello\"\n",
    "print(a is b, a == b)  # True True\n",
    "print(a is not b, a != b)  # False False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "f9c2fb23-0870-43cf-8480-12b347451344",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False True\n",
      "True False\n"
     ]
    }
   ],
   "source": [
    "#比较的两个变量均指向可变类型。\n",
    "a = [\"hello\"]\n",
    "b = [\"hello\"]\n",
    "print(a is b, a == b)  # False True\n",
    "print(a is not b, a != b)  # True False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "5c7915b7-1fb5-4579-8956-e4f6d18635e9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-9\n",
      "0.1111111111111111\n",
      "0\n",
      "-12.5\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "运算符\t        描述\n",
    "**\t            指数（最高优先级）\n",
    "~+-\t            按位翻转，一元加号和减号\n",
    "* / % //\t    乘，除，取模和取整除）\n",
    "+ -\t            加法减法\n",
    ">> <<\t        右移，左移运算符\n",
    "&\t            位‘AND’\n",
    "^|\t            位运算符\n",
    "<=<>>=\t        比较运算符\n",
    "<>==!=\t        等于运算符\n",
    "=%=/=//=-=+==*=\t赋值运算符\n",
    "is is not\t    身份运算符\n",
    "in not in\t    成员运算符\n",
    "not and or\t    逻辑运算符\n",
    "'''\n",
    "\n",
    "print(-3 ** 2)  # -9  \n",
    "print(3 ** -2)  # 0.1111111111111111\n",
    "print(1 << 3 + 2 & 7)  # 0\n",
    "print(-3 * 2 + 5 / -2 - 4)  # -12.5\n",
    "print(3 < 4 and 4 < 5)  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "7550c9f5-5db9-402f-a3be-39b13cf59a44",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "老马的程序人生\n",
      "5\n",
      "老马的程序人生,小马的程序人生\n",
      "学习\n"
     ]
    }
   ],
   "source": [
    "teacher = \"老马的程序人生\"\n",
    "print(teacher)  # 老马的程序人生\n",
    "\n",
    "first = 2\n",
    "second = 3\n",
    "third = first + second\n",
    "print(third)  # 5\n",
    "\n",
    "myTeacher = \"老马的程序人生\"\n",
    "yourTeacher = \"小马的程序人生\"\n",
    "ourTeacher = myTeacher + ',' + yourTeacher\n",
    "print(ourTeacher)  # 老马的程序人生,小马的程序人生\n",
    "\n",
    "# 运行一下就好啦\n",
    "set_1 = {\"欢迎\", \"学习\",\"Python\"}\n",
    "print(set_1.pop())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "caefe0c8-29d9-46d0-8149-15b30a62065b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1031 <class 'int'>\n",
      "['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']\n",
      "0b10000000111\n",
      "11\n"
     ]
    }
   ],
   "source": [
    "# 数据类型与转换\n",
    "'''\n",
    "类型\t名称\t                示例\n",
    "int\t    整型<class 'int'>\t    -876, 10\n",
    "float\t浮点型<class 'float'>\t3.149, 11.11\n",
    "bool\t布尔型<class 'bool'>\tTrue, False\n",
    "'''\n",
    "#整型\n",
    "a = 1031\n",
    "print(a, type(a))\n",
    "# 1031 <class 'int'>\n",
    "\n",
    "'''\n",
    "dir(int) 会返回一个包含整数（int 类型）所有可用属性和方法名称的列表。\n",
    "当执行 b = dir(int) 时，变量 b 会被赋值为这个列表。列表中包含了 int 类型内置的各种方法，例如：\n",
    "基本运算相关的 __add__（加法）、__sub__（减法）等\n",
    "转换相关的 __str__（转为字符串）、__float__（转为浮点数）等\n",
    "其他实用方法如 bit_length（获取二进制表示的位数）、is_integer 等\n",
    "'''\n",
    "b = dir(int)\n",
    "print(b)\n",
    "\n",
    "\n",
    "a = 1031\n",
    "print(bin(a))  # 0b10000000111\n",
    "print(a.bit_length())  # 11\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "c8f5d073-176f-467d-95b8-fc67c725240c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.0 <class 'float'>\n",
      "2.3e-07\n",
      "2.3e-07\n"
     ]
    }
   ],
   "source": [
    "\n",
    "#浮点型\n",
    "print(1., type(1.))\n",
    "# 1.0 <class 'float'>\n",
    "\n",
    "a = 0.00000023\n",
    "b = 2.3e-7\n",
    "print(a)  # 2.3e-07\n",
    "print(b)  # 2.3e-07\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "f7123f3d-ef2d-4372-8ec4-36c254df11b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])\n",
      "0.3333333333333333333333333333\n",
      "0.3333\n"
     ]
    }
   ],
   "source": [
    "import decimal\n",
    "from decimal import Decimal\n",
    "\n",
    "# getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。\n",
    "a = decimal.getcontext()\n",
    "print(a)\n",
    "\n",
    "b = Decimal(1) / Decimal(3)\n",
    "print(b)\n",
    "# 0.3333333333333333333333333333\n",
    "\n",
    "#保留思维精度\n",
    "decimal.getcontext().prec = 4\n",
    "c = Decimal(1) / Decimal(3)\n",
    "print(c)\n",
    "\n",
    "# 0.3333"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "f65724dd-4d88-4a82-8613-dc2608b1e57c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "1\n",
      "0\n",
      "<class 'int'> False True\n",
      "<class 'float'> False True\n",
      "<class 'bool'> False True\n",
      "<class 'str'> False True\n",
      "<class 'tuple'> False True\n",
      "<class 'list'> False True\n",
      "<class 'dict'> False True\n",
      "<class 'set'> False True\n"
     ]
    }
   ],
   "source": [
    "#布尔型\n",
    "print(True + True)  # 2\n",
    "print(True + False)  # 1\n",
    "print(True * False)  # 0\n",
    "\n",
    "print(type(0), bool(0), bool(1))\n",
    "# <class 'int'> False True\n",
    "\n",
    "print(type(10.31), bool(0.00), bool(10.31))\n",
    "# <class 'float'> False True\n",
    "\n",
    "print(type(True), bool(False), bool(True))\n",
    "# <class 'bool'> False True\n",
    "\n",
    "print(type(''), bool(''), bool('python'))\n",
    "# <class 'str'> False True\n",
    "\n",
    "print(type(()), bool(()), bool((10,)))\n",
    "# <class 'tuple'> False True\n",
    "\n",
    "print(type([]), bool([]), bool([1, 2]))\n",
    "# <class 'list'> False True\n",
    "\n",
    "print(type({}), bool({}), bool({'a': 1, 'b': 2}))\n",
    "# <class 'dict'> False True\n",
    "\n",
    "print(type(set()), bool(set()), bool({1, 2}))\n",
    "# <class 'set'> False True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "eff385c4-a811-4585-b7d0-054399fb3352",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "#获取类型信息\n",
    "'''\n",
    "注：\n",
    "type() 不会认为子类是一种父类类型，不考虑继承关系。\n",
    "isinstance() 会认为子类是一种父类类型，考虑继承关系。\n",
    "如果要判断两个类型是否相同推荐使用 isinstance()。\n",
    "'''\n",
    "print(isinstance(1, int))  # True\n",
    "print(isinstance(5.2, float))  # True\n",
    "print(isinstance(True, bool))  # True\n",
    "print(isinstance('5.2', str))  # True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "965789f0-8310-4c0f-88f6-3deb5bf5230d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "520\n",
      "520\n",
      "520.52\n",
      "520.0\n",
      "20\n",
      "15.3\n"
     ]
    }
   ],
   "source": [
    "#类型转换\n",
    "print(int('520'))  # 520\n",
    "print(int(520.52))  # 520\n",
    "print(float('520.52'))  # 520.52\n",
    "print(float(520))  # 520.0\n",
    "print(str(10 + 10))  # 20\n",
    "print(str(10.1 + 5.2))  # 15.3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "4c73e14f-31f2-4ff9-ad58-23b5a9065c0e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is printed without 'end'and 'sep'.\n",
      "apple\n",
      "mango\n",
      "carrot\n",
      "banana\n",
      "\n",
      "This is printed with 'end='&''.\n",
      "apple&mango&carrot&banana&hello world\n",
      "\n",
      "This is printed with 'sep='&''.\n",
      "apple&another string\n",
      "mango&another string\n",
      "carrot&another string\n",
      "banana&another string\n"
     ]
    }
   ],
   "source": [
    "#print() 函数\n",
    "'''\n",
    "将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出；\n",
    "关键字参数sep是实现分隔符，比如多个参数输出时想要输出中间的分隔字符；\n",
    "关键字参数end是输出结束时的字符，默认是换行符\\n；\n",
    "关键字参数file是定义流输出的文件，可以是标准的系统输出sys.stdout，也可以重定义为别的文件；\n",
    "关键字参数flush是立即把内容输出到流文件，不作缓存。\n",
    "print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
    "'''\n",
    "shoplist = ['apple', 'mango', 'carrot', 'banana']\n",
    "print(\"This is printed without 'end'and 'sep'.\")\n",
    "for item in shoplist:\n",
    "    print(item)\n",
    "\n",
    "\n",
    "print(\"\")\n",
    "print(\"This is printed with 'end='&''.\")\n",
    "for item in shoplist:\n",
    "    print(item, end='&')\n",
    "print('hello world')\n",
    "\n",
    "\n",
    "print(\"\")\n",
    "print(\"This is printed with 'sep='&''.\")\n",
    "for item in shoplist:\n",
    "    print(item, 'another string', sep='&')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "1dc3d086-a6af-4680-9117-da7b8bbc71a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "1\n",
      "16\n",
      "0\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "#通过 <<，>> 快速计算2的倍数问题。\n",
    "\n",
    "n = 2\n",
    "m = 3\n",
    "print(n << 1) # 计算 n*2\n",
    "print(n >> 1) # 计算 n/2，负奇数的运算不可用\n",
    "print(n << m) # 计算 n*(2^m)，即乘以 2 的 m 次方\n",
    "print(n >> m) # 计算 n/(2^m)，即除以 2 的 m 次方\n",
    "print(1 << n) # 2^n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "e10612a2-637e-4717-99b9-e5bf6a6218e4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "#通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。\n",
    "a = 5\n",
    "b = 6\n",
    "a ^= b\n",
    "b ^= a\n",
    "a ^= b\n",
    "print(a)\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "a9f6ffb7-4f30-4869-af18-e74a72322e6f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b101\n",
      "-0b101\n",
      "1\n",
      "\n",
      "0b110\n",
      "-0b110\n",
      "2\n",
      "\n",
      "0b1100\n",
      "-0b1100\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "#通过 a & (-a) 快速获取a的最后为 1 位置的整数\n",
    "print( bin(5) )\n",
    "print( bin(-5) )\n",
    "print( 5 & -5 )\n",
    "\n",
    "print('')\n",
    "print( bin(6) )\n",
    "print( bin(-6) )\n",
    "print( 6 & -6 )\n",
    "\n",
    "print('')\n",
    "print( bin(12) )\n",
    "print( bin(-12) )\n",
    "print( 12 & -12 )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "c8089eb0-d277-415e-8650-532f97e09a95",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b11\n",
      "-0b11\n",
      "0b11111111111111111111111111111101\n",
      "0b11111111111111111111111111111101\n",
      "4294967293\n"
     ]
    }
   ],
   "source": [
    "#输出二进制\n",
    "\n",
    "print(bin(3))  # 0b11\n",
    "print(bin(-3))  # -0b11\n",
    "\n",
    "print(bin(-3 & 0xffffffff))  \n",
    "# 0b11111111111111111111111111111101\n",
    "\n",
    "print(bin(0xfffffffd))       \n",
    "# 0b11111111111111111111111111111101\n",
    "\n",
    "print(0xfffffffd)  # 4294967293"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "807ec4e0-606a-4a27-bb59-b08ce19a968f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Correct Judgement!\n"
     ]
    }
   ],
   "source": [
    "if 2 > 1 and not 2 > 3:\n",
    "    print('Correct Judgement!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "d8465aee-171c-48c8-a51a-3f28035f7d28",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "猜一猜小姐姐想的是哪个数字？ 666\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你太了解小姐姐的心思了！\n",
      "哼，猜对也没有奖励！\n",
      "游戏结束，不玩儿啦！\n"
     ]
    }
   ],
   "source": [
    "temp = input(\"猜一猜小姐姐想的是哪个数字？\")\n",
    "guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。\n",
    "if guess == 666:\n",
    "    print(\"你太了解小姐姐的心思了！\")\n",
    "    print(\"哼，猜对也没有奖励！\")\n",
    "else:\n",
    "    print(\"猜错了，小姐姐现在心里想的是666！\")\n",
    "print(\"游戏结束，不玩儿啦！\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "f3562cd4-819d-4709-901e-dbac472ef155",
   "metadata": {},
   "outputs": [],
   "source": [
    "hi = 6\n",
    "if hi > 2:\n",
    "    if hi > 7:\n",
    "        print('好棒!好棒!')\n",
    "else:\n",
    "    print('切~')\n",
    "\n",
    "# 无输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "f994368a-1dae-4643-83a9-5c432e31892b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "猜一猜小姐姐想的是哪个数字？ 6\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "小了，小了\n",
      "游戏结束，不玩儿啦！\n"
     ]
    }
   ],
   "source": [
    "temp = input(\"猜一猜小姐姐想的是哪个数字？\")\n",
    "guess = int(temp)\n",
    "if guess > 8:\n",
    "    print(\"大了，大了\")\n",
    "else:\n",
    "    if guess == 8:\n",
    "        print(\"你太了解小姐姐的心思了！\")\n",
    "        print(\"哼，猜对也没有奖励！\")\n",
    "    else:\n",
    "        print(\"小了，小了\")\n",
    "print(\"游戏结束，不玩儿啦！\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "2b7561ec-0725-4aee-a3d4-f8b5e2df2034",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入成绩: 89\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "B\n"
     ]
    }
   ],
   "source": [
    "temp = input('请输入成绩:')\n",
    "source = int(temp)\n",
    "if 100 >= source >= 90:\n",
    "    print('A')\n",
    "elif 90 > source >= 80:\n",
    "    print('B')\n",
    "elif 80 > source >= 60:\n",
    "    print('C')\n",
    "elif 60 > source >= 0:\n",
    "    print('D')\n",
    "else:\n",
    "    print('输入错误！')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "698a829b-fc4b-4cea-a35d-6623ecafe381",
   "metadata": {},
   "outputs": [
    {
     "ename": "AssertionError",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAssertionError\u001b[0m                            Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[52], line 4\u001b[0m\n\u001b[0;32m      2\u001b[0m my_list \u001b[38;5;241m=\u001b[39m [\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlsgogroup\u001b[39m\u001b[38;5;124m'\u001b[39m]\n\u001b[0;32m      3\u001b[0m my_list\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;241m0\u001b[39m)\n\u001b[1;32m----> 4\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(my_list) \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m0\u001b[39m\n",
      "\u001b[1;31mAssertionError\u001b[0m: "
     ]
    }
   ],
   "source": [
    "#assert 关键词\n",
    "my_list = ['lsgogroup']\n",
    "my_list.pop(0)\n",
    "assert len(my_list) > 0\n",
    "\n",
    "# AssertionError"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "fe2a5ec1-a49b-492b-97e5-8e3a8f8e17f8",
   "metadata": {},
   "outputs": [
    {
     "ename": "AssertionError",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAssertionError\u001b[0m                            Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[53], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;241m3\u001b[39m \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m7\u001b[39m\n",
      "\u001b[1;31mAssertionError\u001b[0m: "
     ]
    }
   ],
   "source": [
    "assert 3 > 7\n",
    "\n",
    "# AssertionError"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "92bd76ea-657a-4980-adfe-f34b30986f9e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "猜一猜小姐姐想的是哪个数字？ 8\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你太了解小姐姐的心思了！\n",
      "哼，猜对也没有奖励！\n",
      "游戏结束，不玩儿啦！\n"
     ]
    }
   ],
   "source": [
    "count = 0\n",
    "while count < 3:\n",
    "    temp = input(\"猜一猜小姐姐想的是哪个数字？\")\n",
    "    guess = int(temp)\n",
    "    if guess > 8:\n",
    "        print(\"大了，大了\")\n",
    "    else:\n",
    "        if guess == 8:\n",
    "            print(\"你太了解小姐姐的心思了！\")\n",
    "            print(\"哼，猜对也没有奖励！\")\n",
    "            count = 3\n",
    "        else:\n",
    "            print(\"小了，小了\")\n",
    "    count = count + 1\n",
    "print(\"游戏结束，不玩儿啦！\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "e4c830cc-15dd-4b0e-b95e-a186b0d45522",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcd\n",
      "bcd\n",
      "cd\n",
      "d\n"
     ]
    }
   ],
   "source": [
    "#布尔表达式返回0，循环终止。\n",
    "string = 'abcd'\n",
    "while string:\n",
    "    print(string)\n",
    "    string = string[1:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "e95ee67f-7074-45e9-bb0a-42d64c6332d6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 is  less than 5\n",
      "1 is  less than 5\n",
      "2 is  less than 5\n",
      "3 is  less than 5\n",
      "4 is  less than 5\n",
      "5 is not less than 5\n"
     ]
    }
   ],
   "source": [
    "#当while循环正常执行完的情况下，执行else输出。\n",
    "count = 0\n",
    "while count < 5:\n",
    "    print(\"%d is  less than 5\" % count)\n",
    "    count = count + 1\n",
    "else:\n",
    "    print(\"%d is not less than 5\" % count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "a8a7396b-76cf-4bbc-b2b9-b7d4ac9636ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 is  less than 5\n",
      "1 is  less than 5\n",
      "2 is  less than 5\n",
      "3 is  less than 5\n"
     ]
    }
   ],
   "source": [
    "#如果while循环中执行了跳出循环的语句，比如 break，将不执行else代码块的内容。\n",
    "count = 0\n",
    "while count < 5:\n",
    "    print(\"%d is  less than 5\" % count)\n",
    "    if count == 3:\n",
    "        break\n",
    "    count = count + 1\n",
    "else:\n",
    "    print(\"%d is not less than 5\" % count)\n",
    "\n",
    "# 0 is  less than 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "6f90ec07-a5ca-476e-8225-a8eb6cb29d97",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I L o v e L S G O \n",
      "直接循环数组\n",
      "张三\n",
      "李四\n",
      "刘德华\n",
      "刘六\n",
      "周润发\n",
      "\n",
      "通过数组下标，循环数组\n",
      "张三\n",
      "李四\n",
      "刘德华\n",
      "刘六\n",
      "周润发\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "for循环是迭代循环，在Python中相当于一个通用的序列迭代器，可以遍历任何有序序列，如str、list、tuple等，也可以遍历任何可迭代对象，如dict。\n",
    "\n",
    "for 迭代变量 in 可迭代对象:\n",
    "    代码块\n",
    "每次循环，迭代变量被设置为可迭代对象的当前元素，提供给代码块使用。\n",
    "'''\n",
    "\n",
    "for i in 'ILoveLSGO':\n",
    "    print(i, end=' ')  # 不换行输出\n",
    "\n",
    "\n",
    "print(\"\")\n",
    "print(\"直接循环数组\")\n",
    "member = ['张三', '李四', '刘德华', '刘六', '周润发']\n",
    "for each in member:\n",
    "    print(each)\n",
    "\n",
    "print(\"\")\n",
    "print(\"通过数组下标，循环数组\")\n",
    "#range(3) 生成 [0,1,2]\n",
    "for i in range(len(member)):\n",
    "    print(member[i])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "553e81ee-6461-46db-98fd-74fb5cc5954e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a:1 b:2 c:3 d:4 "
     ]
    }
   ],
   "source": [
    "#循环对象，并拼接\n",
    "dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n",
    "\n",
    "for key, value in dic.items():\n",
    "    print(key, value, sep=':', end=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "80c46086-df63-468b-b69f-eec58be02bc1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a b c d "
     ]
    }
   ],
   "source": [
    "# 循环对象的key\n",
    "dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n",
    "\n",
    "for key in dic.keys():\n",
    "    print(key, end=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "1488714f-68f3-46cc-b9ca-c48a72defb0d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2 3 4 "
     ]
    }
   ],
   "source": [
    "# 循环对象的值\n",
    "\n",
    "dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n",
    "\n",
    "for value in dic.values():\n",
    "    print(value, end=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "0447e53e-f264-4f60-a984-729a51399027",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 等于 2 * 5\n",
      "11 是一个质数\n",
      "12 等于 2 * 6\n",
      "13 是一个质数\n",
      "14 等于 2 * 7\n",
      "15 等于 3 * 5\n",
      "16 等于 2 * 8\n",
      "17 是一个质数\n",
      "18 等于 2 * 9\n",
      "19 是一个质数\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "当for循环正常执行完的情况下，执行else输出，如果for循环中执行了跳出循环的语句，比如 break，将不执行else代码块的内容，与while - else语句一样。\n",
    "for - else 循环\n",
    "for 迭代变量 in 可迭代对象:\n",
    "    代码块\n",
    "else:\n",
    "    代码块\n",
    "'''\n",
    "\n",
    "for num in range(10, 20):  # 迭代 10 到 20 之间的数字\n",
    "    for i in range(2, num):  # 根据因子迭代\n",
    "        if num % i == 0:  # 确定第一个因子\n",
    "            j = num / i  # 计算第二个因子\n",
    "            print('%d 等于 %d * %d' % (num, i, j))\n",
    "            break  # 跳出当前循环\n",
    "    else:  # 循环的 else 部分\n",
    "        print(num, '是一个质数')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "79e293d6-b706-44a9-bca0-3172ef6f027d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7\n",
      "8\n",
      "\n",
      "小于5\n",
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "\n",
      "步长为2\n",
      "1\n",
      "3\n",
      "5\n",
      "7\n",
      "9\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "range() 函数¶\n",
    "range([start,] stop[, step=1])\n",
    "这个BIF（Built-in functions）有三个参数，其中用中括号括起来的两个表示这两个参数是可选的。\n",
    "step=1 表示第三个参数的默认值是1。\n",
    "range 这个BIF的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列，该序列包含start的值但不包含stop的值。\n",
    "'''\n",
    "for i in range(2, 9):  # 不包含9\n",
    "    print(i)\n",
    "\n",
    "\n",
    "print(\"\")\n",
    "print(\"小于5\")\n",
    "for i in range(5):\n",
    "    print(i)\n",
    "    \n",
    "print(\"\")\n",
    "print(\"步长为2\")\n",
    "for i in range(1, 10, 2):\n",
    "    print(i)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "35d266c1-dd30-4afb-ae7f-994e28cf0095",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]\n",
      "\n",
      "[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]\n",
      "\n",
      "I love Python\n",
      "I love R\n",
      "I love Matlab\n",
      "I love C++\n",
      "Done!\n",
      "\n",
      "2 I love Python\n",
      "3 I love R\n",
      "4 I love Matlab\n",
      "5 I love C++\n",
      "Done!\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "enumerate()函数\n",
    "enumerate(sequence, [start=0])\n",
    "sequence：一个序列、迭代器或其他支持迭代对象。\n",
    "start：下标起始位置。\n",
    "返回 enumerate(枚举) 对象\n",
    "'''\n",
    "\n",
    "seasons = ['Spring', 'Summer', 'Fall', 'Winter']\n",
    "lst = list(enumerate(seasons))\n",
    "print(lst)\n",
    "\n",
    "#用 enumerate(A) 不仅返回了 A 中的元素，还顺便给该元素一个索引值 (默认从 0 开始)。此外，用 enumerate(A, j) 还可以确定索引起始值为 j。\n",
    "print(\"\")\n",
    "lst = list(enumerate(seasons, start=1))  # 下标从 1 开始\n",
    "print(lst)\n",
    "\n",
    "\n",
    "print(\"\")\n",
    "languages = ['Python', 'R', 'Matlab', 'C++']\n",
    "for language in languages:\n",
    "    print('I love', language)\n",
    "print('Done!')\n",
    "\n",
    "\n",
    "print(\"\")\n",
    "for i, language in enumerate(languages, 2):\n",
    "    print(i, 'I love', language)\n",
    "print('Done!')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "c984519d-e742-4c40-81a8-06d3b02048d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "#pass是空语句，不做任何操作，只起到占位的作用，其作用是为了保持程序结构的完整性。\n",
    "#尽管pass语句不做任何操作，但如果暂时不确定要在一个位置放上什么样的代码，可以先放置一个pass语句，让代码可以正常运行。\n",
    "\n",
    "def a_func():\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "89a409e6-2a55-4dc3-8980-a8ec90959891",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-8, -4, 0, 4, 8]\n"
     ]
    }
   ],
   "source": [
    "#列表推导式  [ expr for value in collection [if condition] ]\n",
    "x = [-4, -2, 0, 2, 4]\n",
    "y = [a * 2 for a in x]\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "ff11e77a-aef3-4111-8913-afd5754da836",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25, 36, 49, 64, 81]\n"
     ]
    }
   ],
   "source": [
    "x = [i ** 2 for i in range(1, 10)]\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "94ae6d90-271d-4761-a803-af6e0ced9b30",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]\n"
     ]
    }
   ],
   "source": [
    "x = [(i, i ** 2) for i in range(6)]\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "114a2c84-27be-4ff4-aa29-ee75e2096a7c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]\n"
     ]
    }
   ],
   "source": [
    "x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "a1e324ae-feb2-4b8a-9f67-0de341b150fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n"
     ]
    }
   ],
   "source": [
    "a = [(i, j) for i in range(0, 3) for j in range(0, 3)]\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "168bac51-3898-40a9-98d6-8d2eb67a2c4b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]\n",
      "[[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]\n"
     ]
    }
   ],
   "source": [
    "x = [[i, j] for i in range(0, 3) for j in range(0, 3)]\n",
    "print(x)\n",
    "\n",
    "x[0][0] = 10\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "30bc4ea1-559f-4818-9ea4-3be7a81ec607",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(0, 2)]\n"
     ]
    }
   ],
   "source": [
    "a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "460b72eb-34e6-4d48-a227-3fa3d671ad0a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<generator object <genexpr> at 0x0000011B4331A0B0>\n",
      "(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n"
     ]
    }
   ],
   "source": [
    "#元组推导式 ( expr for value in collection [if condition] )\n",
    "a = (x for x in range(10))\n",
    "print(a)\n",
    "\n",
    "# <generator object <genexpr> at 0x0000025BE511CC48>\n",
    "\n",
    "print(tuple(a))\n",
    "\n",
    "# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "ee4a6568-ffa9-4f91-a538-913e8043ce3e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0: True, 3: False, 6: True, 9: False}\n"
     ]
    }
   ],
   "source": [
    "#字典推导式 { key_expr: value_expr for value in collection [if condition] }\n",
    "b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}\n",
    "print(b)\n",
    "# {0: True, 3: False, 6: True, 9: False}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "4b888939-7704-4050-aba3-f057896bb1ce",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5, 6}\n"
     ]
    }
   ],
   "source": [
    "#集合推导式 { expr for value in collection [if condition] }\n",
    "c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}\n",
    "print(c)\n",
    "# {1, 2, 3, 4, 5, 6}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "a801f4cd-ceae-43f1-8446-b7cd41879afb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<generator object <genexpr> at 0x0000011B4331A5F0>\n",
      "0\n",
      "1\n",
      "2 3 4 5 6 7 8 9 "
     ]
    }
   ],
   "source": [
    "e = (i for i in range(10))\n",
    "print(e)\n",
    "# <generator object <genexpr> at 0x0000007A0B8D01B0>\n",
    "\n",
    "print(next(e))  # 0\n",
    "print(next(e))  # 1\n",
    "\n",
    "for each in e:\n",
    "    print(each, end=' ')\n",
    "\n",
    "# 2 3 4 5 6 7 8 9"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "509ebee9-b73d-4277-b9ea-0da34140e629",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5050\n",
      "5050\n"
     ]
    }
   ],
   "source": [
    "s = sum([i for i in range(101)])\n",
    "print(s)  # 5050\n",
    "s = sum((i for i in range(101)))\n",
    "print(s)  # 5050"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "525654d3-efbe-4562-a71c-7f4686d90e34",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "打开文件出错\n"
     ]
    }
   ],
   "source": [
    "#try - except 语句\n",
    "try:\n",
    "    f = open('test.txt')\n",
    "    print(f.read())\n",
    "    f.close()\n",
    "except OSError:\n",
    "    print('打开文件出错')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "id": "04b000c2-0e5b-4c95-a747-9b54a0985fbf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "打开文件出错\n",
      "原因是：[Errno 2] No such file or directory: 'test.txt'\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    f = open('test.txt')\n",
    "    print(f.read())\n",
    "    f.close()\n",
    "except OSError as error:\n",
    "    print('打开文件出错\\n原因是：' + str(error))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "id": "16eab79a-ebf4-4b18-b0c6-a1eaf9b31a50",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数值出错\n",
      "原因是：invalid literal for int() with base 10: 'abc'\n"
     ]
    }
   ],
   "source": [
    "#一个try语句可能包含多个except子句，分别来处理不同的特定的异常。最多只有一个分支会被执行。\n",
    "try:\n",
    "    int(\"abc\")\n",
    "    s = 1 + '1'\n",
    "    f = open('test.txt')\n",
    "    print(f.read())\n",
    "    f.close()\n",
    "except OSError as error:\n",
    "    print('打开文件出错\\n原因是：' + str(error))\n",
    "except TypeError as error:\n",
    "    print('类型出错\\n原因是：' + str(error))\n",
    "except ValueError as error:\n",
    "    print('数值出错\\n原因是：' + str(error))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "364e6f9b-e19f-45a2-863b-958504afd027",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "查询错误\n",
      "键错误\n"
     ]
    }
   ],
   "source": [
    "dict1 = {'a': 1, 'b': 2, 'v': 22}\n",
    "try:\n",
    "    x = dict1['y']\n",
    "except LookupError:\n",
    "    print('查询错误')\n",
    "except KeyError:\n",
    "    print('键错误')\n",
    "else:\n",
    "    print(x)\n",
    "\n",
    "# 查询错误\n",
    "'''\n",
    "try-except-else语句尝试查询不在dict中的键值对，从而引发了异常。\n",
    "这一异常准确地说应属于KeyError，但由于KeyError是LookupError的子类，且将LookupError置于KeyError之前，因此程序优先执行该except代码块。\n",
    "所以，使用多个except代码块时，必须坚持对其规范排序，要从最具针对性的异常到最通用的异常。\n",
    "'''\n",
    "dict1 = {'a': 1, 'b': 2, 'v': 22}\n",
    "try:\n",
    "    x = dict1['y']\n",
    "except KeyError:\n",
    "    print('键错误')\n",
    "except LookupError:\n",
    "    print('查询错误')\n",
    "else:\n",
    "    print(x)\n",
    "\n",
    "# 键错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "id": "91a27a32-9215-4d92-935f-91b349b055a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "出错了！\n",
      "原因是：unsupported operand type(s) for +: 'int' and 'str'\n"
     ]
    }
   ],
   "source": [
    "#一个 except 子句可以同时处理多个异常，这些异常将被放在一个括号里成为一个元组。\n",
    "try:\n",
    "    s = 1 + '1'\n",
    "    int(\"abc\")\n",
    "    f = open('test.txt')\n",
    "    print(f.read())\n",
    "    f.close()\n",
    "except (OSError, TypeError, ValueError) as error:\n",
    "    print('出错了！\\n原因是：' + str(error))\n",
    "\n",
    "# 出错了！\n",
    "# 原因是：unsupported operand type(s) for +: 'int' and 'str'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "965c102b-e455-4c20-bc58-9d8b12aea4e4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result is 2.0\n",
      "executing finally clause\n",
      "division by zero!\n",
      "executing finally clause\n",
      "executing finally clause\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "unsupported operand type(s) for /: 'str' and 'str'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[83], line 23\u001b[0m\n\u001b[0;32m     20\u001b[0m divide(\u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m0\u001b[39m)\n\u001b[0;32m     21\u001b[0m \u001b[38;5;66;03m# division by zero!\u001b[39;00m\n\u001b[0;32m     22\u001b[0m \u001b[38;5;66;03m# executing finally clause\u001b[39;00m\n\u001b[1;32m---> 23\u001b[0m \u001b[43mdivide\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43m2\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43m1\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "Cell \u001b[1;32mIn[83], line 9\u001b[0m, in \u001b[0;36mdivide\u001b[1;34m(x, y)\u001b[0m\n\u001b[0;32m      7\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21mdivide\u001b[39m(x, y):\n\u001b[0;32m      8\u001b[0m     \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m----> 9\u001b[0m         result \u001b[38;5;241m=\u001b[39m \u001b[43mx\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m/\u001b[39;49m\u001b[43m \u001b[49m\u001b[43my\u001b[49m\n\u001b[0;32m     10\u001b[0m         \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mresult is\u001b[39m\u001b[38;5;124m\"\u001b[39m, result)\n\u001b[0;32m     11\u001b[0m     \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mZeroDivisionError\u001b[39;00m:\n",
      "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'str'"
     ]
    }
   ],
   "source": [
    "'''\n",
    "try - except - finally 语句¶\n",
    "try: 检测范围 except Exception[as reason]: 出现异常后的处理代码 finally: 无论如何都会被执行的代码\n",
    "\n",
    "不管try子句里面有没有发生异常，finally子句都会执行。\n",
    "'''\n",
    "def divide(x, y):\n",
    "    try:\n",
    "        result = x / y\n",
    "        print(\"result is\", result)\n",
    "    except ZeroDivisionError:\n",
    "        print(\"division by zero!\")\n",
    "    finally:\n",
    "        print(\"executing finally clause\")\n",
    "\n",
    "\n",
    "divide(2, 1)\n",
    "# result is 2.0\n",
    "# executing finally clause\n",
    "divide(2, 0)\n",
    "# division by zero!\n",
    "# executing finally clause\n",
    "divide(\"2\", \"1\")\n",
    "# executing finally clause\n",
    "# TypeError: unsupported operand type(s) for /: 'str' and 'str'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "8b3df88f-3353-4314-9c20-a426c7bf117a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "An exception flew by!\n"
     ]
    }
   ],
   "source": [
    "#Python 使用raise语句抛出一个指定的异常。\n",
    "try:\n",
    "    raise NameError('HiThere')\n",
    "except NameError:\n",
    "    print('An exception flew by!')\n",
    "    \n",
    "# An exception flew by!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a740c15a-8eba-4687-b6e2-ed00599c0e5c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.23"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
